package leetCode;



public class T151A2 {
    public static void main(String[] args) {
        new SolutionT151A2().reverseWords(" asdasd df f");
    }
}
class SolutionT151A2 {
    public String reverseWords(String s) {
        char[] chars = s.toCharArray();
        reverse(chars,0,chars.length-1);
        int k=0;
        for (int i=0;i<s.length();i++){
            if (chars[i]==' ')continue;
            int curTmp=i;
            while (i<s.length()&&chars[i]!=' '){
                i++;
            }
            reverse(chars,curTmp,i-1);
            for (int j=curTmp;j<i;j++){
                chars[k]=chars[j];
                k++;
                if (j==i-1){
                    if (k<s.length()){
                        chars[k++]=' ';
                    }

                }
            }

        }
        if (k==0){
            return "";
        }else {
            return new String(chars,0,(k==s.length())&& (chars[k - 1] != ' ')?k:k-1);
        }

    }
    public void reverse(char chars[],int src,int dest){
        int ti=src;
        int tj=dest;
        while (ti<tj){
            char temp=chars[ti];
            chars[ti]=chars[tj];
            chars[tj]=temp;
            ti++;
            tj--;
        }
    }
}